package com.wangdong.wdutils.utils;



import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * json管理
 * 
 * @author Administrator
 * 
 */
public class DLJsonUtil {

    private DLJsonUtil() {
        throw new AssertionError();
    }

    /**
     * 检查字符串是否是json格式的
     * @param json String
     * @return boolean
     */
    public static boolean isGoodJson(String json) {

        try {
            new JsonParser().parse(json);
            return true;
        } catch (JsonParseException e) {
            return false;
        }
    }

	/**
     * 将返回的JSON数据转换为对象的其它类型
     * @param <T> T
     * @param jsonString String
     * @param cls Class
     * @return T
     */
    public static <T> T getPerson(String jsonString, Class<T> cls) {
        	T t = null;
        	try {
        		Gson gson = new Gson();
        		t = gson.fromJson(jsonString, cls);
        	} catch (Exception e) {
        		e.printStackTrace();
        	}
        	return t;
    	}
		
    public static <T> List<T> getPersons(String jsonString, Class<T[]> cls) {
        List<T> list = null;
        try {
           Gson gson = new Gson();
            list = Arrays.asList(gson.fromJson(jsonString, cls));
         } catch (Exception e) {
             e.printStackTrace();
         }
         return list;
     }
		 
    public static List<String> getStrings(String jsonString) {
    	 List<String> list = null;
         try {
            Gson gson = new Gson();
             list = gson.fromJson(jsonString, new TypeToken<List<String>>() {
             }.getType());
         } catch (Exception e) {
             e.printStackTrace();
         }
         return list;
     }
		 
    public static List<HashMap<String, Object>> getMaps(String jsonString) {
         List<HashMap<String, Object>> list = new ArrayList<>();
         try {
           Gson gson = new GsonBuilder().registerTypeAdapter(new TypeToken<List<HashMap<String, Object>>>() {
                   }.getType(),
                   new JsonDeserializer<List<HashMap<String, Object>>>() {
                       @Override
                       public List<HashMap<String, Object>> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

                           List<HashMap<String, Object>> tempList = new ArrayList<>();

                           JsonArray tempArray = json.getAsJsonArray();

                           for (int i=0;i<tempArray.size();i++){
                               JsonElement tempDic = tempArray.get(i);
                               if (tempDic!=null){
                                   JsonObject jsonObject = tempDic.getAsJsonObject();
                                   HashMap<String, Object> treeMap = new HashMap<>();

                                   Set<Map.Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
                                   for (Map.Entry<String, JsonElement> entry : entrySet) {
                                       treeMap.put(entry.getKey(), entry.getValue());
                                   }
                                   tempList.add(treeMap);
                               }
                           }

                           return tempList;
                       }
                   }).create();
            list = gson.fromJson(jsonString, new TypeToken<List<HashMap<String, Object>>>() {
             }.getType());
        } catch (Exception e) {
            e.printStackTrace();
         }
         return list;
     }

    public static  HashMap<String, Object> getMap(String jsonString) {

        HashMap<String, Object> map = new HashMap<>();
        try {
            Gson gson = new GsonBuilder().registerTypeAdapter(new TypeToken<HashMap<String, Object>>() {
                    }.getType(),
                    new JsonDeserializer<HashMap<String, Object>>() {
                        @Override
                        public HashMap<String, Object> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

                            HashMap<String, Object> treeMap = new HashMap<>();
                            JsonObject jsonObject = json.getAsJsonObject();
                            Set<Map.Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
                            for (Map.Entry<String, JsonElement> entry : entrySet) {
                                treeMap.put(entry.getKey(), entry.getValue());
                            }
                            return treeMap;

                        }
                    }).create();
            map = gson.fromJson(jsonString, new TypeToken<HashMap<String, Object>>(){}.getType());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
	
    /**
     * 将返回的JSON数据转换为对象
     * @param <T> T
     * @param json String
     * @param classOfT Class
     * @return T
     */
	public static <T> T object(String json, Class<T> classOfT) {
        Gson gson = new Gson();
		return gson.fromJson(json, classOfT);
	}
    
	/**
	 * 将对象转换为JSON数据
     * @param <T> T
	 * @param param CLass
	 * @return String
	 */
	public static <T> String toJson(Class<T> param) {
        Gson gson = new Gson();
		return gson.toJson(param);
	}


    /**
     * 判断json是否存在key
     * @param object JSONObject
     * @param key String
     * @return boolean
     */
    public static boolean notEmptyAndHas(JSONObject object, String key) {
        return object != null && !DLStringUtil.isEmpty(key) && object.has(key);
    }

    /**
     * 获取json中Object
     * @param object JSONObject
     * @param key Stirng
     * @return Object
     */
    public static Object hasAndGetObject(JSONObject object, String key){
    	Object tempO = null;
    	
    	if(notEmptyAndHas(object, key)){
    		try {
				tempO = object.get(key);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}
    	}
		return tempO;
    }

    /**
     * 获取JSONObject中JSONArray
     * @param object JSONObject
     * @param key Stirng
     * @return JSONArray
     */
    public static JSONArray hasAndGetJsonArray(JSONObject object, String key){
    	JSONArray tempO = null;
    	if(notEmptyAndHas(object, key)){
    		try {
				tempO = object.getJSONArray(key);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}
    	}
    	return tempO;
    }

    /**
     * 获取JSONArray中JSONObject
     * @param array JSONArray
     * @param index int
     * @return JSONObject
     */
    public static JSONObject hasAndGetJsonObjectFromJsonArray(JSONArray array, int index){
    	JSONObject tempO = null;
    	if(array!=null && array.length()>index){
    		try {
				tempO = array.getJSONObject(index);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}
    	}
    	return tempO;
    }

    /**
     * 获取json中JSONObject
     * @param object JSONObject
     * @param key String
     * @return JSONObject
     */
    public static JSONObject hasAndGetJsonObject(JSONObject object, String key){
    	JSONObject tempO = null;
    	if(notEmptyAndHas(object, key)){
    		try {
				tempO = object.getJSONObject(key);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}
    	}
    	return tempO;
    }

    /**
     * 获取json中String
     * @param object JSONObject
     * @param key String
     * @return String
     */
    public static String hasAndGetString(JSONObject object, String key){
    	String tempO = null;
    	if(notEmptyAndHas(object, key)){
    		try {
				tempO = object.getString(key);
				if(tempO == null){
					tempO = null;
				}else if(tempO.equals("null")){
					tempO = null;
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}
    	}
    	return tempO;
    }

    /**
     * 获取json中long
     * @param object JSONObject
     * @param key String
     * @return long
     */
    public static Long hasAndGetLong(JSONObject object, String key){
        Long tempO = null;
        if(notEmptyAndHas(object, key)){
            try {
                tempO = object.getLong(key);
            } catch (JSONException e) {
                //e.printStackTrace();
            }
        }
        return tempO;
    }

    /**
     * 获取json中double
     * @param object JSONObject
     * @param key String
     * @return double
     */
    public static Double hasAndGetDouble(JSONObject object, String key){
        Double tempO = null;
        if(notEmptyAndHas(object, key)){
            try {
                tempO = object.getDouble(key);
            } catch (JSONException e) {
                //e.printStackTrace();
            }
        }
        return tempO;
    }

    /**
     * 获取json中int
     * @param object JSONObject
     * @param key Stirng
     * @return Integer
     */
    public static Integer hasAndGetInt(JSONObject object, String key){
    	Integer tempO = 0;
    	if(notEmptyAndHas(object, key)){
    		try {
				tempO = object.getInt(key);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}
    	}
    	return tempO;
    }

    /**
     * 获取json中BigDecimal等同于long
     * @param object JSONObject
     * @param key String
     * @return BigDecimal
     */
    public static BigDecimal hasAndGetBigDecimal(JSONObject object,String key){
        BigDecimal tempO = null;
        if (notEmptyAndHas(object,key)){
            try {
                String ex = object.getString(key);
                if (DLStringUtil.notEmpty(ex)) {
                    tempO = new BigDecimal(ex);
                }else{
                    tempO = new BigDecimal("0");
                }
            } catch (JSONException e) {
                try {
                    tempO = new BigDecimal(object.getLong(key));
                } catch (JSONException e1) {
//                    e1.printStackTrace();
                }
            }
        }
        return tempO;
    }

    /**
     * 获取json中boolean
     * @param object JSONObject
     * @param key String
     * @return boolean
     */
    public static boolean hasAndGetBoolean(JSONObject object, String key){
    	boolean tempO = false;
    	if(notEmptyAndHas(object, key)){
    		try {
				int tempint = object.getInt(key);
				tempO = tempint==1?true:false;
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
				
				try {
					tempO = object.getBoolean(key);
				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					//e1.printStackTrace();
				}
			}
    	}
    	return tempO;
    }
}
